package com.ftg.learn.test1.book1;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * 用户类
 *
 * @author lijiaxin
 * @version 1.0
 * @date 2023/8/9 8:49
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name;
    private volatile Book[] books;
    private int index=0;

    public User(String name){
        this.name=name;
        books=new Book[6];
    }

    public synchronized void lendbook(Book book){
        //我要多一本书
        if (index == books.length || book.getCount() == 0) {
            throw new RuntimeException("您已经借阅了足够多的书");
        }
        this.books[index++] = book;
        //书的库存量 - 1
        book.setCount(book.getCount() - 1);

        //生成一个记录
        BorrowRecord br = new BorrowRecord();
        br.setUser(this);
        br.setBook(book);
        br.setLendTime(LocalDateTime.now().toString());
    }

    public synchronized void returnbook(int index){
        if (index < 0 || index > this.index || this.index == 0) {
            throw new RuntimeException("请正确还书");
        }

        //2 书的当量  + 1
        books[index].setCount(books[index].getCount() + 1);

        //3 记录
        BorrowRecord br = new BorrowRecord();
        br.setUser(this);
        br.setBook(books[index]);
        br.setReturnTie(LocalDateTime.now().toString());

        System.out.println(br);
        // 1 数组减去一个
        //        1.1
        if (index != books.length - 1) {
            System.arraycopy(this.books, index + 1, this.books, index, this.books.length - index-1);

        }
        books[this.index] = null;
        this.index--;

    }
}
